<?php

namespace app\test514\controller;

use app\test514\model\User;
use think\Controller;
use think\Request;
use think\Validate;

class Login extends Controller
{
    //先调用视图文件
    /**
     *Method index
     * @return \think\response\View
     *user:大飞
     *time:2021/5/14 9:16
     */
    public function index()
    {
        return view('login/index');
    }


    /**
     * 数据处理
     *Method login
     *user:大飞
     *time:2021/5/14 9:17
     */
    public function login()
    {

        $data = input();
        $data['password'] = md5(md5($data['password']));

        //验证
        $result = $this->Validate($data, [
            'tel' => 'require|max:11|/^1[3-8]{1}[0-9]{9}$/',
            'password' => 'require'
        ], [
            'tel' => '手机号不能为空|手机号码最多不能超过11个字符|手机号格式不正确',
            'password.require' => '密码不能为空',
        ]);
        if (true !== $result) {
            // 验证失败 输出错误信息
            $this->error($result);
        }

        //根据条件查询单条数据
        $res = User::where('tel', $data['tel'])->find();

        if (!$res) {
            $this->error('手机号错误');
        } else {
            if ($data['password'] != $res['password']) {
                $this->error('密码错误');
            }


            session('token',$res['token']);
            session('userInfo',$res);
            return redirect('test514/Article/index');
        }


    }

    //退出登录
    public function loginOut()
    {
        //清除session
        session(null);

        return redirect('test514/login/index');
    }
}
